package com.china08.yxyapi.api.home.kecheng.xiaoben;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;

/**
 * 校本课程--列表页--按一级、二级、是否付费、已受权 进行课程查询
 * 
 * @author LiuWeidong
 *
 */
@CrossOrigin
@RestController
public class KechengXiaobenListSrhController extends YxyApiBaseController {

    @Autowired
    JdbcTemplate JdbcTemplate;

    @RequestMapping(value = "/api_yw/home/kecheng/xiaoben/list/srh", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public RespModel find(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {

        // String roleId = getProfile(request, response).getRoleId();
        // String userId = getProfile(request, response).getId();
        String schoolId = getProfile(request, response).getSchoolId();
        String oneId = reqModel.oneId;
        String twoId = reqModel.twoId;
        Integer status = reqModel.status;
        String lastModifiedDate = reqModel.lastModifiedDate;
        String ep = reqModel.ep;
        String pv = reqModel.pv;
        String statusMe = reqModel.statusMe;
        String name = (StringUtils.isNotBlank(reqModel.name)) ? "%" + reqModel.name + "%" : "";
        Integer pageNum = reqModel.pageNum;
        List<String> studentList = reqModel.studentList;

        // List<String> studentList = new ArrayList<>();
        List<Object> paramList = new ArrayList<Object>();

        RespModel respModel = new RespModel();
        List<Pojo> returnList = new ArrayList<>();
        Integer allPage = 0;

        // /** 如果用户角色为学生 */
        // if (StringUtils.contains(roleId, SystemConstant.ROLE_STUDENT)) {
        // studentList.add(userId);
        // }

        // /** 如果用户角色为家长 */
        // if (StringUtils.contains(roleId, SystemConstant.ROLE_PARENTS)) {
        // studentList = studentIdList(userId);
        // } else {
        // studentList.add(userId);
        // }

        // 授权给我的
        if (statusMe.equals("1")) {

            List<Object> paramList2 = new ArrayList<>();
            StringBuffer sb1 = new StringBuffer();
            sb1.append("  select    DISTINCT                                                  ");
            sb1.append("    t2.id,                                                            ");
            sb1.append("    t2.name,                                                          ");
            sb1.append("    t2.vip,                                                           ");
            sb1.append("    t2.catalog_id2,t2.cover,t2.count,t2.duration,t2.name,t2.ep,t2.vv ,");
            sb1.append("   if(t1.user_id is null, '0', '1') as auth                           ");
            sb1.append("  from                                                                ");
            sb1.append("    yxy_lessons.yxy_lessons_school_lesson_auth t1                     ");
            sb1.append("    left join yxy_lessons.yxy_lessons_school_lesson t2                ");
            sb1.append("      on (t1.lesson_id = t2.id)                                       ");
            sb1.append("    where t2.school_id = ?                                            ");
            sb1.append("    and t2.status = 2                                                 ");
            sb1.append("    and t2.is_Visible = 1                                             ");
            paramList2.add(schoolId);
            if (StringUtils.isNotBlank(oneId)) {
                sb1.append(" and t2.catalog_id1 = ?                                           ");
                paramList2.add(oneId);
            }
            if (StringUtils.isNotBlank(twoId)) {
                sb1.append(" and t2.catalog_id2 = ?                                           ");
                paramList2.add(twoId);
            }
            // if (status != null) {
            // sb1.append(" and (t1.user_id is null, '0', '1') = ? ");
            // paramList2.add(status);
            // }
            if (StringUtils.isNotBlank(name)) {
                sb1.append(" and t1.name like ?                                               ");
                paramList2.add(name);
            }
            if (studentList.size() > 0) {
                sb1.append("  and t1.user_id in (                                             ");
            }
            for (int i = 0; i < studentList.size(); i++) {
                if (i == studentList.size() - 1) {
                    sb1.append(" ?)   ");
                } else {
                    sb1.append("?,   ");
                }
                paramList2.add(studentList.get(i));
            }
            List<Map<String, Object>> list = JdbcTemplate.queryForList(sb1.toString(), paramList2.toArray());
            allPage = list.size();

            // 最近更新、评分最高、学习最多 排序
            if (StringUtils.isNotBlank(lastModifiedDate)) {
                sb1.append(" ORDER BY t2.create_date DESC                                         ");
            }
            if (StringUtils.isNotBlank(ep) && StringUtils.isBlank(lastModifiedDate)) {
                sb1.append(" ORDER BY t2.ep DESC                                              ");
            }
            if (StringUtils.isNotBlank(pv) && StringUtils.isBlank(ep) && StringUtils.isBlank(lastModifiedDate)) {
                sb1.append(" ORDER BY t2.vv DESC                                              ");
            }
            sb1.append(" limit ?,?                                                            ");
            paramList2.add((pageNum - 1) * 20);
            paramList2.add(20);
            list = JdbcTemplate.queryForList(sb1.toString(), paramList2.toArray());

            for (Map<String, Object> map : list) {
                String catalogId2 = map.get("catalog_id2") + "";
                String sql = " select name from yxy_lessons.yxy_lessons_school_catalog where id = ? ";
                Map<String, Object> cataMap = JdbcTemplate.queryForMap(sql, new Object[] { catalogId2 });
                String catalogName = cataMap.get("name") + "";

                Pojo pojo = new Pojo();
                pojo.vip = true;
                pojo.userVip = true;
                pojo.twoName = catalogName;
                pojo.kechengVip = (Integer.parseInt(map.get("vip") + "") == 1) ? true : false;

                pojo.cover = map.get("cover") + "";
                pojo.name = map.get("name") + "";
                pojo.lessonId = map.get("id") + "";
                pojo.count = Integer.parseInt(map.get("count") + "");
                pojo.duration = Integer.parseInt(map.get("duration") + "");
                pojo.ep = Float.parseFloat(map.get("ep") + "");
                pojo.vv = Integer.parseInt(map.get("vv") + "");

                returnList.add(pojo);
            }
        }

        // 不是授权给我的
        else {

            StringBuffer sb1 = new StringBuffer();
            sb1.append(" select distinct                                                          ");
            sb1.append("   t1.id,                                                                 ");
            sb1.append("   t1.vip,                                                                ");
            sb1.append("   t1.catalog_id2,t1.cover,t1.count,t1.duration,t1.name,t1.ep,t1.vv,t1.id,");
            sb1.append("   if(t2.user_id is null, '0', '1') as auth                               ");
            sb1.append(" from                                                                     ");
            sb1.append("   yxy_lessons.yxy_lessons_school_lesson t1                               ");
            sb1.append("   left join yxy_lessons.yxy_lessons_school_lesson_auth t2                ");
            sb1.append("     on (t1.id = t2.lesson_id)                                            ");
            sb1.append(" where t1.school_id = ?                                                   ");
            sb1.append("   and t1.status = 2                                                      ");
            sb1.append("   and t1.is_Visible = 1                                                  ");
            paramList.add(schoolId);

            if (StringUtils.isNotBlank(oneId)) {
                sb1.append(" and t1.catalog_id1 = ?                                               ");
                paramList.add(oneId);
            }
            if (StringUtils.isNotBlank(twoId)) {
                sb1.append(" and t1.catalog_id2 = ?                                               ");
                paramList.add(twoId);
            }
            // if (status != null) {
            // sb1.append(
            // " and if(t2.user_id is null, '0', '1') = ? ");
            // paramList.add(status);
            // }
            if (status != null) {
                sb1.append(" and t1.vip = ?                                                       ");
                paramList.add(status);
            }
            if (StringUtils.isNotBlank(name)) {
                sb1.append(" and t1.name like ?                                                   ");
                paramList.add(name);
            }
            List<Map<String, Object>> listMaps = JdbcTemplate.queryForList(sb1.toString(), paramList.toArray());
            allPage = listMaps.size();

            // 最近更新、评分最高、学习最多 排序
            if (StringUtils.isNotBlank(lastModifiedDate)) {
                sb1.append(" ORDER BY t1.create_date DESC                                             ");
            }
            if (StringUtils.isNotBlank(ep) && StringUtils.isBlank(lastModifiedDate)) {
                sb1.append(" ORDER BY t1.ep DESC                                                  ");
            }
            if (StringUtils.isNotBlank(pv) && StringUtils.isBlank(ep) && StringUtils.isBlank(lastModifiedDate)) {
                sb1.append(" ORDER BY t1.vv DESC                                                  ");
            }

            sb1.append(" limit ?,?                                                                ");
            paramList.add((pageNum - 1) * 20);
            paramList.add(20);
            listMaps = JdbcTemplate.queryForList(sb1.toString(), paramList.toArray());

            for (Map<String, Object> map : listMaps) {
                String lessonId = map.get("id") + "";
                String auth = map.get("auth") + "";

                String catalogId2 = map.get("catalog_id2") + "";
                String sql = " select name from yxy_lessons.yxy_lessons_school_catalog where id = ? ";
                Map<String, Object> cataMap = JdbcTemplate.queryForMap(sql, new Object[] { catalogId2 });
                String catalogName = cataMap.get("name") + "";

                Pojo pojo = new Pojo();
                pojo.twoName = catalogName;
                pojo.cover = map.get("cover") + "";
                pojo.name = map.get("name") + "";
                pojo.lessonId = map.get("id") + "";
                pojo.count = Integer.parseInt(map.get("count") + "");
                pojo.duration = Integer.parseInt(map.get("duration") + "");
                pojo.ep = Float.parseFloat(map.get("ep") + "");
                pojo.vv = Integer.parseInt(map.get("vv") + "");
                pojo.kechengVip = (Integer.parseInt(map.get("vip") + "") == 1) ? true : false;
                // 未授权课程
                if (auth.equals("0")) {
                    pojo.vip = false;
                    pojo.userVip = false;
                }

                // 授权课程
                else {
                    pojo.vip = true;

                    List<Object> paramList2 = new ArrayList<>();

                    StringBuffer sb2 = new StringBuffer();
                    sb2.append("  select                                               ");
                    sb2.append("    user_id                                            ");
                    sb2.append("  from                                                 ");
                    sb2.append("    yxy_lessons.yxy_lessons_school_lesson_auth         ");
                    sb2.append("  where lesson_id = ?                                  ");
                    paramList2.add(lessonId);

                    if (studentList.size() > 0) {
                        sb2.append(" and user_id in (                                  ");
                    }
                    for (int i = 0; i < studentList.size(); i++) {
                        if (i == studentList.size() - 1) {
                            sb2.append("?)   ");
                        } else {
                            sb2.append("?,   ");
                        }
                        paramList2.add(studentList.get(i));
                    }

                    List<Map<String, Object>> list = JdbcTemplate.queryForList(sb2.toString(), paramList2.toArray());
                    pojo.userVip = list.size() > 0;
                }
                returnList.add(pojo);
            }
        }

        respModel.list = returnList;
        respModel.allPage = allPage;
        return respModel;
    }

    // public List<String> studentIdList(String userId) {
    // List<String> list = new ArrayList<>();
    // String sql = " select student_id from
    // china08_yunxiao_pro.rel_student_guardian where guardian_id = ? ";
    // List<Map<String, Object>> listMaps = JdbcTemplate.queryForList(sql, new
    // Object[] { userId });
    // for (Map<String, Object> map : listMaps) {
    // list.add(map.get("student_id") + "");
    // }
    // return list;
    // }

    public static class Pojo {
        public String twoName;
        public String cover;
        public Integer count;
        public Integer duration;
        public String name;
        public Float ep;
        public Integer vv;
        public String lessonId;
        public Boolean vip; // 已授权
        public Boolean userVip; // 用户授权
        public Boolean kechengVip; // 课程授权
    }

    /* 请求参数 */
    protected static class ReqModel extends YxyApiPageReqModel {

        // 用户Id
        public List<String> studentList;

        // 一级ID
        public String oneId;

        // 二级ID
        public String twoId;

        // 课程名称
        public String name;

        // 状态:0-未授权,1-已授权
        public Integer status;

        // 按最近更新排序(如果点击前台传“1”)
        public String lastModifiedDate;

        // 按评分最高排序(如果点击前台传“1”)
        public String ep;

        // 按学习最多排序(如果点击前台传“1”)
        public String pv;

        // 已授给我的课程(如果点击前台传“1”)
        public String statusMe;
        public Integer pageNum;
    }

    /* 响应参数 */
    protected static class RespModel extends YxyApiRespModel {
        public List<Pojo> list;
        public Integer allPage;
    }
}
